package com.ceair.flight.refund.util;

import com.ceair.muibe.provider.UserInfo;
import com.ceair.unified.businessobject.rqrs.unicfg.UniMBERS;
import com.ceair.unified.ws.unicfgmanager.IUniConfigManagerWS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Date;

@Component
public class CeairUtils {
	public static final String LPAD_STR = "0";
	public static final int STR_LENGTH = 6;
	public static final int RANDOM_BASE_INT = 1000000;
	private static final Logger LOGGER = LoggerFactory.getLogger(CeairUtils.class);
	private static IUniConfigManagerWS uniConfigManagerWSCommon;

	@Autowired(required=false)
	public void setUniConfigManagerWSCommon(IUniConfigManagerWS uniConfigManagerWSCommon) {
		CeairUtils.uniConfigManagerWSCommon = uniConfigManagerWSCommon;
	}

	final static char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
								  'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 
								  'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
								  'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
								  'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
								  'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
								  'Y', 'Z'};	

	public static String compressLongNo(BigInteger bi) {
		char[] buf = new char[64];
		int charPos = 64;
		String radix = "52";
		do {
			int mod=bi.mod(new BigInteger(radix)).intValue();
			buf[--charPos] = digits[mod];
			bi=new BigInteger(bi.divide(new BigInteger(radix)).toString());
		} while (!bi.toString().equals("0"));
		return new String(buf, charPos, (64 - charPos));
	}

	/*
	 * 把16进制字符串转换成字节数组 @param hex @return
	 */
	public static byte[] hexStringToByte(String hex) {
		int len = (hex.length() / 2);
		byte[] result = new byte[len];
		char[] achar = hex.toUpperCase().toCharArray();
		for (int i = 0; i < len; i++) {
			int pos = i * 2;
			result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
		}
		return result;
	}

	private static byte toByte(char c) {
		byte b = (byte) "0123456789ABCDEF".indexOf(c);
		return b;
	}

	private static final String ALGORITHM = "DESede";

	// keybyte为加密密钥，长度为24字节
	// src为被加密的数据缓冲区（源）
	public static byte[] encryptMode(byte[] keybyte, byte[] src) {
		try {
			// 生成密钥
			SecretKey deskey = new SecretKeySpec(keybyte, ALGORITHM);

			// 加密
			Cipher c1 = Cipher.getInstance(ALGORITHM);
			c1.init(Cipher.ENCRYPT_MODE, deskey);
			return c1.doFinal(src);
		} catch (java.security.NoSuchAlgorithmException e1) {
			LOGGER.error(e1.getMessage());
			// e1.printStackTrace();
		} catch (javax.crypto.NoSuchPaddingException e2) {
			LOGGER.error(e2.getMessage());
			// e2.printStackTrace();
		} catch (Exception e3) {
			LOGGER.error(e3.getMessage());
			// e3.printStackTrace();
		}
		return null;
	}

	// keybyte为加密密钥，长度为24字节
	// src为加密后的缓冲区
	public static byte[] decryptMode(byte[] keybyte, byte[] src) {
		try {
			// 生成密钥
			SecretKey deskey = new SecretKeySpec(keybyte, ALGORITHM);

			// 解密
			Cipher c1 = Cipher.getInstance(ALGORITHM);
			c1.init(Cipher.DECRYPT_MODE, deskey);
			return c1.doFinal(src);
		} catch (java.security.NoSuchAlgorithmException e1) {
			LOGGER.error(e1.getMessage());
			// e1.printStackTrace();
		} catch (javax.crypto.NoSuchPaddingException e2) {
			LOGGER.error(e2.getMessage());
			// e2.printStackTrace();
		} catch (Exception e3) {
			LOGGER.error(e3.getMessage());
			// e3.printStackTrace();
		}
		return null;
	}

	// 转换成十六进制字符串
	public static String byte2hex(byte[] b) {
		StringBuffer hs = new StringBuffer("");
		String stmp = "";

		for (int n = 0; n < b.length; n++) {
			stmp = (Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1) {

				hs.append("0");
				hs.append(stmp);
			} else {
				hs.append(stmp);
			}

		}
		return hs.toString().toUpperCase();
	}

	/**
	 * 
	 * @return 获取mbe接口调用用户信息
	 */
    /*public static UserInfo getUserInfo() {
        UserInfo user = new UserInfo();
        user.setChannelId(ConfigUtil.getStringValue("g_channelId"));
        user.setChannelPwd(ConfigUtil.getStringValue("g_channelPwd"));
        return user;
    }*/

	/**
	 * 
	 * @return 获取mbe接口调用用户信息
	 */
    /*public static UserInfo getUserInfo(String channelId,String channelPwd) {
        UserInfo user = new UserInfo();
        user.setChannelId(channelId);
        user.setChannelPwd(channelPwd);
        return user;
    }*/

	/**
	 * 
	 * @return 获取mbe接口调用用户信息
	 */
    public static UserInfo getUserInfo(String channelCode) {
    	UniMBERS uniMBERS = uniConfigManagerWSCommon.findMBEChannelByChannel(Long.parseLong(channelCode));
        UserInfo user = new UserInfo();
        user.setChannelId(uniMBERS.getMbeUsername());
        user.setChannelPwd(uniMBERS.getMbePassword());
        return user;
    }
    
    public static void main(String[] args) {
    	System.out.println(compressLongNo(new BigInteger("9016090600000111111609060000011419")).length());
	}
    
    /** 
     * 将Date类转换为XMLGregorianCalendar 
     * @param date 
     * @return  
     */  
    public static XMLGregorianCalendar dateToXmlDate(Date date){  
            Calendar cal = Calendar.getInstance();  
            cal.setTime(date);  
            DatatypeFactory dtf = null;  
             try {  
                dtf = DatatypeFactory.newInstance();  
            } catch (DatatypeConfigurationException e) {  
            }  
            XMLGregorianCalendar dateType = dtf.newXMLGregorianCalendar();  
            dateType.setYear(cal.get(Calendar.YEAR));  
            //由于Calendar.MONTH取值范围为0~11,需要加1  
            dateType.setMonth(cal.get(Calendar.MONTH)+1);  
            dateType.setDay(cal.get(Calendar.DAY_OF_MONTH));  
            dateType.setHour(cal.get(Calendar.HOUR_OF_DAY));  
            dateType.setMinute(cal.get(Calendar.MINUTE));  
            dateType.setSecond(cal.get(Calendar.SECOND));  
            return dateType;  
        } 
}
